﻿#!/usr/bin/env node

import dow from "@baige/wget"
import getDown from './modules/HuaJun/getDown'
import search from "./modules/tencent/search"
import lookup from "./modules/lookup"
import perform from "./modules/perform"
import color from "./modules/color"
process.stdin.setEncoding('utf8');
let headers:any = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.44"}

// 先获取参数
let type:any = process.argv.splice(2);
type[0] = type[0]?.replace(/^[-]*/,"")
switch (type[0]){
    case "d":
    case "download":{
        console.log(type[1])
        // 直接下载连接
        dow(type[1],{dir:process.cwd(),headers:headers}).then(e=>{
            if(e){
                console.log("文件下载完成");
                console.log("开始执行安装");
                perform(e)
            }else{
                console.log("下载失败")
            }
        })
        break;
    }
    case "i":
    case "install":{
        lookup(type[1]).then((e:any)=>{
            if(e){
                // console.log("开始下载")
                dow(e.url,{dir:process.cwd(),headers:e.headers || headers}).then(e=>{
                    if(e){
                        console.log("文件下载完成");
                        console.log("开始执行安装");
                        perform(e)
                    }else{
                        console.log("下载失败")
                    }
                })
            }else{
                search(type[1]).then(async (e:any)=>{
                    if(e.code !== 0){
                        console.log("未找到这个软件的链接");
                        return;
                    }
                    // 执行下载
                    dow(e.list[0].url,{dir:process.cwd(),headers:e.headers || headers}).then(e=>{
                        if(e){
                            console.log("文件下载完成");
                            console.log("开始执行安装");
                            perform(e)
                        }else{
                            console.log("下载失败")
                        }
                    })
                })
            }
        })
        break;
    }
    case "s":
    case "search":{
        search(type[1]).then(async (e:any)=>{
            if(e.code !== 0){
                console.log("未找到这个软件的链接");
                return;
            }
            e.list.map((e:any,i:any)=>{
                console.log(i+1,color("白色",e.SoftName),color("绿色","\t"+(Number(e.size)/1024/1024).toFixed(2)+"MB"),color("黄色",e.time))
            })
        
            let index = undefined;
            while(true){
                process.stdout.write("请选择：");
                index = Number(await readlineSync());
                if(index > e.length || index < 1){
                    console.log("超出范围,请重新输入")
                    continue;
                }
                break;
            }
            // 执行下载
            dow(e.list[index-1].url,{dir:process.cwd(),headers:e.headers || headers}).then(e=>{
                if(e){
                    console.log("文件下载完成");
                    console.log("开始执行安装");
                    perform(e)
                }else{
                    console.log("下载失败")
                }
            })


        })
        break;
    }
    case "-v":
    case "v":{
        console.log("version: 1.0.3")
    }
    default :{
        console.log(`
-[全称] or -[首字母] or [首字母]

-download [网址]             执行下载

-install  [软件名]           从软件库中查找安装，软件有可能不存在
        
-search   [软件名]           从华军软件市场查找软件
        `)
    }
}



// 根据华软的页面链接进行下载
function pagn_dow(url:string){
    return new Promise(ress=>{
        // 从华软获取下载链接
        getDown(url).then((e:any)=>{
            // 默认用第一个下载
            if(e.length===0){
                console.log("未找到下载链接")
                return
            }
            // 华军软件园请求头 一定要设置Referer字段，不然会报404
            headers.Referer = e[0].url;
            // 进行下载
            dow(e[0].url,{dir:process.cwd(),headers}).then((e:string)=>ress(e))
        })
    })
}


/**
 * 读取控制台命令
 * @returns 
 */
function readlineSync() {
    return new Promise((resolve, reject) => {
        process.stdin.resume();
        process.stdin.on('data', function (data:string) {
            process.stdin.pause(); // 在读取一行后停止
            resolve(data.replace(/[\r\n]/g,""));
            
        });
    });
}




// set-ExecutionPolicy RemoteSigned
// npm config set registry http://registry.npm.taobao.org
// npm publish --access public